<template>
    <div>
      <ShoppingCart :cart-items="cartItems" :loading="loading" :error="error"  @update-cart="fetchCartData" />
    </div>
</template>

<script>
import ShoppingCart from "@/components/ShoppingCart.vue";
import { fetchCartGoods, fetchGoodDetails} from "@/apis/cart";
import { useUserStore } from "@/stores/user";

export default {
  components: {
    ShoppingCart,
  },
  data() {
    return {
      cartItems: [], // 存储购物车数据
      loading: true, // 数据加载状态
      error: null, // 错误信息
    };
  },
  setup() {
    const userStore = useUserStore();
    const userId = userStore.userAInfo.userId; // 从 Pinia 获取 userId
    return {
      userId,
    };
  },
  methods: {
    async fetchCartData() {
      try {
        if (!this.userId) throw new Error("Customer ID not found in localStorage.");

        const cartGoods = await fetchCartGoods(this.userId);
        const cartItemsPromises = cartGoods.map(async (cartItem) => {
          const goodDetails = await fetchGoodDetails(cartItem.goodId);
          // 打印 imageUrl
        console.log(`Image URL for item ${cartItem.goodId}:`, goodDetails.imageUrl);

          return {
            ...cartItem,
            imageUrl: goodDetails.imageUrl,
            name: goodDetails.goodsName,
            price: goodDetails.price,
            quantity: cartItem.carCount,
          };
        });

        this.cartItems = await Promise.all(cartItemsPromises);
      } catch (err) {
        this.error = err.message || "Failed to fetch cart data.";
      } finally {
        this.loading = false;
      }
    },
  },
  mounted() {
    this.fetchCartData();
  },
};
</script>
